from .conn_mysql import Connect_Mysql

from .phone_test import is_phone,verify_name

import pymysql

from flask import request

from . import app_register

@app_register.route('/register',methods = ['POST'])

def register():

    info = request.form
    company_name = info.get('company_name')
    linkman = info.get('linkman')
    phone = info.get('phone')
    need = info.get('need')
    party = info.get('party')
    openid = info.get('openid')

    sql = 'insert into company(company_name,linkman,phone,need,party)values(%s,%s,%s,%s,%s)'

    if not all((company_name,linkman,phone,need,party)):#and not is_phone(phone):

        return {
                    'status': -1,
                    'errorCode': '1',
                    'errorMsg': '参数错误',
                    'resultBody': None
                }
    if not is_phone(phone):

        return {
                'status': -1,
                'errorCode': 2,
                'errorMsg': f'请检查你的{phone}',
                'resultBody': None
            }

    if not verify_name(linkman):
    
        return {
            'status': -1,
            'errorCode': 2,
            'errorMsg': f'请检查你的{linkman}',
            'resultBody': None
        }

    if not verify_name(company_name):
        
        return {
            'status': -1,
            'errorCode': 2,
            'errorMsg': f'请检查你的{company_name}',
            'resultBody': None
        }

    with Connect_Mysql() as conn_:

        try:

            info = conn_.insert_company(sql,(company_name,linkman,phone,need,party))
        
        except pymysql.err.IntegrityError as e: #: (1062, "Duplicate entry '77771231231' for key 'phone'")

            if e.args[0] == 1062:
                return {
                    'status': -1,
                    'errorCode': 1062,
                    'errorMsg': e.args[1],
                    'resultBody': None
                }

            else:
                raise

        conn_.update_openid(openid,info['LAST_INSERT_ID()'])
        
    return {
                'status': 1,
                'errorCode':  None,
                'errorMsg': None,
                'resultBody':   info['LAST_INSERT_ID()']
            }